<template>
    <div class="healthy-nav">
        <div class="healthy-nav-top">
            <div class="healthy-nav-title">
                <h3>{{ healthyTitle }}</h3>
            </div>
            <div class="healthy-nav-fun" v-show="addShow">
                <el-button type="primary" plain @click="delCheckedHealthy">删除</el-button>
                <el-button type="primary" @click="addEssay">新增文章</el-button>
            </div>
        </div>
        <div class="healthy-nav-table" v-if="addShow">
            <!-- 搜索区 -->
            <el-form :inline="true" :model="fromEnc" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="fromEnc.user" @blur="searchAuthor" ref="authorName" placeholder="请输入作者姓名"
                        style="width: 320px;"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchAuthor">搜索</el-button>
                </el-form-item>
            </el-form>
            <!-- table区 -->
            <el-table ref="multipleTable" :data="healthyPro.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                tooltip-effect="dark" style="width: 100%" @selection-change="(selection) => { changeCheck(selection) }">
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column prop="textTitle" label="文章标题" align="center">
                </el-table-column>
                <el-table-column label="缩略图" align="center">
                    <img src="../../../public/images/hospital/缩略图.png" style="width: 80px;height: 40px;" alt="">
                </el-table-column>
                <el-table-column prop="author" label="作者" align="center">
                </el-table-column>
                <el-table-column prop="opeDate" label="操作时间" align="center">
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total" class="page-cur"
                @size-change="handleSizeChange" @current-change="handleCurrentChange">
            </el-pagination>
        </div>
        <div class="healthy-nav-from" v-else>
            <div class="healthy-nav-title">编辑文章信息</div>
            <div class="healthy-from">
                <el-form :model="healthyFrom" :rules="rules" ref="healthyFrom" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="文章标题" prop="title">
                        <el-input v-model="healthyFrom.title" placeholder="请输入文章标题" style="width: 320px;"></el-input>
                    </el-form-item>
                    <el-form-item label="上传缩略图" prop="photo">
                        <el-upload action="https://jsonplaceholder.typicode.com/posts/" list-type="picture-card"
                            :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-form-item>
                    <el-form-item label="作者" prop="author">
                        <el-input v-model="healthyFrom.author" placeholder="请输入作者名字" style="width: 320px;"></el-input>
                    </el-form-item>
                    <el-form-item label="文章内容" prop="text">
                        <el-input type="textarea" v-model="healthyFrom.text" style="width: 320px;"></el-input>
                    </el-form-item>
                    <el-form-item label="文章状态" prop="delivery">
                        <el-switch v-model="healthyFrom.delivery"></el-switch>
                    </el-form-item>
                    <el-form-item label="活动时间" prop="data">
                        <el-date-picker v-model="healthyFrom.data" type="datetime" placeholder="选择日期时间"
                            style="width: 320px;">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="preserve('healthyFrom')">保存</el-button>
                        <el-button @click="cancel">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script>
import { getHealthyList, delHealthy, updataHealthy, addHealthy } from "@/api/hospital/healthyEnc";
import { nanoid } from "nanoid";
export default {
    name: 'HealthyEnc',
    data() {
        return {
            // 判断是修改用户还是新增用户
            isupdata: false,
            // 分页器默认显示第一页
            currentPage: 1,
            // 分页器默认每页10条
            pageSize: 10,
            // 分页器总数据
            total: 0,
            // 搜索区
            fromEnc: {
                user: ''
            },
            // table区
            healthyPro: [],
            checkedHealthyPro: [],
            // 新增文章表单
            healthyFrom: {
                title: '',
                author: '',
                text: '',
                data: '',
                delivery: false
            },
            rules: {
                title: [
                    { required: true, message: '请输入文章标题', trigger: 'blur' }
                ],
                photo: [
                    { required: false, message: '请选择照片', trigger: 'blur' }
                ],
                author: [
                    { required: true, message: '请输入作者名字', trigger: 'blur' }
                ],
                text: [
                    { required: false, message: '请输入文章内容', trigger: 'blur' }
                ],
                data: [
                    { required: true, message: '请选择时间', trigger: 'blur' }
                ]
            },
            //健康百科标题
            healthyTitle: '健康百科',
            // 新增按钮是否出现
            addShow: true,
            // 上传图片
            dialogImageUrl: '',
            dialogVisible: false,
        }
    },
    methods: {
        // 搜索
        async searchAuthor() {

            let _val = this.$refs.authorName.value
            if (_val.trim() != '') {
                let _arr = await getHealthyList()
                let _list = []
                _arr.data.forEach(item => {
                    if (item.author.indexOf(_val) >= 0) {
                        _list.push(item)
                    }
                })
                this.healthyPro = _list
                this.currentPage = 1
                this.pageSize = 10
                this.total = this.healthyPro.length
            } else {
                this.getHealthys()
            }

        },
        // 删除选中数据
        delCheckedHealthy() {
            if (confirm('确定要删除所选中的数据吗？')) {
                this.checkedHealthyPro.forEach(async item => {
                    await delHealthy(item.id)
                })
            }

            setTimeout(() => {
                this.getHealthys()
            }, 10)
            this.$message({
                message: '删除成功',
                type: 'success'
            })
        },
        changeCheck(selection) {
            this.checkedHealthyPro = selection
        },
        // table中的编辑按钮
        handleEdit(index, row) {
            this.isupdata = true
            this.addShow = false
            let _date = new Date(row.opeDate)
            this.healthyFrom.id = row.id
            this.healthyFrom.title = row.textTitle
            this.healthyFrom.author = row.author
            this.healthyFrom.data = _date
        },
        // table中的删除按钮
        async handleDelete(index, row) {
            if (confirm('确定要删除吗？')) {
                await delHealthy(row.id)
                this.getHealthys()
            }
        },
        // 分页器
        // 每页多少条数据
        handleSizeChange(val) {
            this.pageSize = val
        },
        // 最新页数
        handleCurrentChange(val) {
            this.currentPage = val
        },
        // 获取最新的健康百科数据
        async getHealthys() {
            let _res = await getHealthyList()
            this.healthyPro = _res.data
            this.total = this.healthyPro.length
        },
        // 新增按钮
        addEssay() {
            this.healthyFrom = {}
            this.isupdata = false
            this.healthyTitle = '新增文章'
            this.addShow = false
        },
        // 保存按钮
        preserve(formName) {
            // 判断是更新用户还是添加用户
            if (this.isupdata) {
                let _id = this.$refs[formName].$options.propsData.model.id
                this.$refs[formName].validate(async (valid) => {
                    if (valid) {
                        this.addShow = true
                        this.healthyTitle = '健康百科'
                        let newData = new Date(this.healthyFrom.data)
                        let year = newData.getFullYear();
                        let month = newData.getMonth();
                        let date = newData.getDate();
                        let hour = newData.getHours();
                        let minute = newData.getMinutes();
                        let second = newData.getSeconds();
                        let result = year + '-' + ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) + '-' + ((date + 1) < 10 ? '0' + date : date) + ' ' + ((hour + 1) < 10 ? '0' + hour : hour) + ':' + ((minute + 1) < 10 ? '0' + minute : minute) + ':' + ((second + 1) < 10 ? '0' + second : second)
                        this.healthyFrom.data = result
                        let arr = {
                            id: _id,
                            textTitle: this.healthyFrom.title,
                            author: this.healthyFrom.author,
                            opeDate: this.healthyFrom.data,
                            isdelete: 0,
                            isChecked: false
                        }
                        await updataHealthy(_id, arr)
                        this.getHealthys()
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        })
                    } else {
                        return false;
                    }
                })
            } else {
                this.$refs[formName].validate(async (valid) => {
                    if (valid) {
                        this.addShow = true
                        this.healthyTitle = '健康百科'
                        // console.log(this.healthyFrom.data);
                        let newData = new Date(this.healthyFrom.data)
                        let year = newData.getFullYear();
                        let month = newData.getMonth();
                        let date = newData.getDate();
                        let hour = newData.getHours();
                        let minute = newData.getMinutes();
                        let second = newData.getSeconds();
                        let result = year + '-' + ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) + '-' + ((date + 1) < 10 ? '0' + date : date) + ' ' + ((hour + 1) < 10 ? '0' + hour : hour) + ':' + ((minute + 1) < 10 ? '0' + minute : minute) + ':' + ((second + 1) < 10 ? '0' + second : second)
                        this.healthyFrom.data = result
                        let arr = {
                            id: nanoid(),
                            textTitle: this.healthyFrom.title,
                            author: this.healthyFrom.author,
                            opeDate: this.healthyFrom.data,
                            isdelete: 0,
                            isChecked: false
                        }
                        await addHealthy(arr)
                        this.getHealthys()
                        this.$message({
                            message: '保存成功',
                            type: 'success'
                        })
                    } else {
                        return false;
                    }
                })
            }
        },
        // 取消按钮
        cancel() {
            this.healthyTitle = '健康百科'
            this.addShow = true
        },
        // 上传图片
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        }
    },
    mounted() {
        this.getHealthys()
    }
}
</script>
<style scoped lang="scss">
.healthy-nav-top {
    display: flex;
    justify-content: space-between;
    height: 70px;

    .healthy-nav-title {
        h3 {
            font-size: 28px;
            margin-left: 50px;
            font-weight: 400;
            position: relative;
        }

        h3::before {
            content: '';
            display: block;
            width: 30px;
            height: 10px;
            background-color: rgba(0, 110, 255, 1);
            position: absolute;
            border-radius: 5px;
            top: 15px;
            left: -50px;
        }
    }
}

.healthy-nav-table {
    width: 100%;
    box-sizing: border-box;
    background: inherit;
    background-color: rgba(255, 255, 255, 1);
    border: none;
    border-radius: 8px;
    box-shadow: 0px 0px 20px rgb(215, 215, 215);
    padding: 20px;
}

.healthy-nav-from {
    width: 100%;
    box-sizing: border-box;
    background: inherit;
    background-color: rgba(255, 255, 255, 1);
    border: none;
    border-radius: 8px;
    box-shadow: 0px 0px 20px rgb(215, 215, 215);

    .healthy-nav-title {
        background-color: rgb(242, 242, 242);
        height: 50px;
        border-radius: 8px 8px 0 0;
        font-size: 16px;
        color: #006EFF;
        line-height: 50px;
        padding-left: 15px;
    }

    .healthy-from {
        padding: 20px;
    }
}
</style>